﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Security.Cryptography;
using System.Text;

namespace WebNext.UI.Utils
{
	class PasswordHelper
	{
		private readonly Byte[] salt;
		private const int GeneratedPasswordLength = 10;

		public PasswordHelper()
		{
			this.salt = new Byte[] { 1, 3, 5, 6, 8, 0, 7, 8, 6, 1 };
		}

		protected virtual HashAlgorithm GetHashAlgorithm()
		{
			return new SHA512CryptoServiceProvider();
		}

		public string Hash(string input)
		{
			HashAlgorithm algorithm = this.GetHashAlgorithm();
			Byte[] inputBytes = Encoding.UTF8.GetBytes(input);

			// Combine salt and input bytes
			Byte[] saltedInput = new Byte[this.salt.Length + inputBytes.Length];
			this.salt.CopyTo(saltedInput, 0);
			inputBytes.CopyTo(saltedInput, this.salt.Length);
			Byte[] hashedBytes = algorithm.ComputeHash(saltedInput);

			return BitConverter.ToString(hashedBytes);
		}
		
		public string Generate()
		{
			StringBuilder passwordBuilder = new StringBuilder();
			Random random = new Random();
			for (int i = 0; i < GeneratedPasswordLength; i++)
			{
				char passwordChar;
				do
				{
					passwordChar = Convert.ToChar(48 + random.Next(75));  // digit and letters scope
				}
				while (!Char.IsLetterOrDigit(passwordChar));
				passwordBuilder.Append(passwordChar);
			}

			return passwordBuilder.ToString();
		}
	}
}